/*                                                                      
    Designer   : Renyangang               
                                                                            
    Licensed under the Apache License, Version 2.0 (the "License");         
    you may not use this file except in compliance with the License.        
    You may obtain a copy of the License at                                 
                                                                            
        http://www.apache.org/licenses/LICENSE-2.0                          
                                                                            
    Unless required by applicable law or agreed to in writing, software    
    distributed under the License is distributed on an "AS IS" BASIS,       
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and     
    limitations under the License. 
*/
import { ref,computed } from 'vue'
import { defineStore } from 'pinia'
import type { BoardConfig, LedData, SwitchData } from '@/scripts/compones';
import { ledConfigStore } from './ledconfig';
import { nixieConfigStore } from './nixie';
import { switchStore } from './switchs';
import { socConfigStore } from './socconfig';
import { GetFileContent, SaveFile, SaveDefaultConfigFile, LoadDefaultConfigFile } from '../../wailsjs/go/main/App';
import { frontend,soc } from '../../wailsjs/go/models';
import { LogError } from '../../wailsjs/runtime/runtime';

export const boardConfigStore = defineStore('boardConfig', () => {
    const boardConfig = ref<BoardConfig>();
    const ledConfig = ledConfigStore();
    const nixieConfig = nixieConfigStore();
    const switchConfig = switchStore();
    const socConfig = socConfigStore();

    async function setBoardConfig(config: BoardConfig) {
        boardConfig.value = config;
        nixieConfig.setNixieConfig(config.nixieConfig);
        await getSocConfig();
        makeLedConfig();
        makeSwitchConfig();
        if (!await SaveDefaultConfigFile(JSON.stringify(config))) {
            LogError("SaveDefaultConfigFile error");
        }
    }

    function makeLedConfig() {
        let ledDatas: LedData[] = [];
        if (socConfig.socConfig && socConfig.socConfig.Leds) {
            for (let i = 0; i < socConfig.socConfig.Leds.LedNumbers; i++) {
                ledDatas.push({
                    id: i,
                    color: socConfig.socConfig.Leds.Color,
                    state: false,
                })
            }
        }
        ledConfig.setLedConfig(ledDatas);
        ledConfig.setLightingMode(socConfig.socConfig?.Leds?.LighingMode == "high");
    }

    function makeSwitchConfig() {
        let switchDatas: SwitchData[] = [];
        if (socConfig.socConfig && socConfig.socConfig.Switchs) {
            for (let i = 0; i < socConfig.socConfig.Switchs.SwitchNumbers; i++) {
                switchDatas.push({
                    id: i,
                    state: false,
                })
            }
        }
        switchConfig.setSwitchsData(switchDatas);
    }

    async function getSocConfig(): Promise<soc.SocConfig> {
        if (!socConfig.socConfig && boardConfig.value && boardConfig.value.socConfigJson.length > 0) {
            await socConfig.saveConfigFromJson(boardConfig.value.socConfigJson);
        } else if (!socConfig.socConfig) {
            await socConfig.loadDefaultConfig();
        }
        return socConfig.socConfig!;
    }

    async function loadConfig() {
        let opt = new frontend.OpenDialogOptions(`{"Title":"Load Config File","Filters":[{"DisplayName":"config","Pattern":"*.json"}]}`)
        let content = await GetFileContent(opt);
        if (content.length > 0) {
            let config = JSON.parse(content);
            await setBoardConfig(config);
        }
    }

    async function saveConfigFile(config: BoardConfig) {
        let opt = new frontend.SaveDialogOptions(`{"Title":"Save Config File","Filters":[{"DisplayName":"config","Pattern":"*.json"}]}`)
        let content = JSON.stringify(config);
        return await SaveFile(content,opt);
    }

    async function saveCurConfigFile() {
        if (boardConfig.value) {
            return await saveConfigFile(boardConfig.value);
        }
    }

    async function loadDefaultConfigFile() {
        let content = await LoadDefaultConfigFile();
        if (content.length > 0) {
            let config = JSON.parse(content);
            await setBoardConfig(config);
        } else {
            init();
        }
    }

    async function init() {
        boardConfig.value = {
            nixieConfig: {
                length: 8,
            },
            socConfigJson: ""
        }
        await setBoardConfig(boardConfig.value);
    }

    return { boardConfig, setBoardConfig,saveCurConfigFile,saveConfigFile,loadConfig,getSocConfig,loadDefaultConfigFile }
})
